import React from 'react'
import { NavLink } from "react-router-dom";
import { Card } from "antd";
import Axios from '../../api/index.jsx';
import './index.less';
import Tool from '../../tool/index.jsx';

const _tool = new Tool();
const { Meta } = Card;


class CardList extends React.Component{
    constructor(props){
      super(props);
      this.state={
        cardList: [],
        num: 12,
        isfirstLoading: true
      }
    }
  componentDidMount() {
    this.getCardList(this.props.keyword);
  }
  componentWillReceiveProps(nextProps){
    if(this.props.keyword !== nextProps.keyword){
      this.getCardList(nextProps.keyword);
    }    
  }
  // 从接口获取菜单列表数据
  getCardList = (keyword) => {
    const num = this.state.num;
    Axios
      .jsonp({
        url: `https://api.jisuapi.com/recipe/search?keyword=${keyword}&num=${num}&appkey=606d66626b732ca1`
      })
      .then(res => {
        if (res.status === 0) {
          this.setState({
            cardList: res.result.list,
            isfirstLoading: false
          })
        }
        else{
          this.setState({
            cardList: [],
            isfirstLoading: false
          })
        }
      },error=>{
        _tool.errorTips(error);
      })
  }

  render() {
    const data = this.state.cardList;
    let listTips =(
          <h3>
            {this.state.isfirstLoading ? '正在加载数据...' : '暂无数据...'} 
          </h3>
      );
    return (
      <div className="content">
        {  data.length !== 0 
           ? data.map((item) => {
              return (
                <NavLink key={item.id} to={{ pathname: `/detail/${item.id}`, state: {pid:item.id} }} >
                 <Card
                    hoverable
                    className="card"
                    cover={<img alt="example" src={item.pic || '../../image/noimage.jpg'} />}
                    id={item.id}
                   >
                    <Meta
                      style={{ whiteSpace: 'nowrap' }}
                      title={item.name}
                      description={item.tag}
                    />
                 </Card>
                </NavLink>
              )
            })
           : <div>{listTips}</div>              
        }
      </div>
    )
  }
}
export default CardList;